<route lang="jsonc" type="page">
  {
    "layout": "tabbar",
    "style": {
      "navigationStyle": "custom",
      "navigationBarTitleText": "个人中心"
    }
  }
  </route>

<script lang="ts" setup>
import { useToast, useUpload, useMessage  } from 'wot-design-uni'
import type { UploadFileItem } from 'wot-design-uni/components/wd-upload/types'
import DiaBasicInfoForm from './components/DiaBasicInfoForm.vue'
import PopCertificateList from './components/PopCertificateList.vue'
import PopScoreList from './components/PopScoreList.vue'
import PopPasswordSetting from './components/PopPasswordSetting.vue'
import { fileUploadNoDomainUrl } from '@/api/common'
import { getUserInfo, updateWorkerAvatar, getUploadQualificationOptions } from '@/api/userInfo'
import type { QualificationOptionType } from '@/api/userInfo'
import { getAccessToken, removeToken, LogOutFn } from '@/utils/auth'

const src = ref<string>('')
const show = ref<boolean>(false)
const basic_info_form = ref(null)
const certificate_list = ref(null)
const score_list = ref(null)
const password_setting = ref(null)
const qualificationOptions = ref<Array<QualificationOptionType>>([])
const toast = useToast()
const message = useMessage()
const userInfo = ref({
  nickname: '',
  avatar: '',
  rating: '',
  completeOrderCount: '',
  applauseRate: null,
  monthCompleteOrderCount: '',
})

const renderInfo = computed(() => {
  const {applauseRate} = userInfo.value
  const applauseRate_format = applauseRate === 0 ? 0 : (applauseRate>0 ? `${applauseRate}%`: '--')
  return {
    ...userInfo.value,
    applauseRate_format
  }
})
function upload() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFilePaths[0]
      src.value = tempFilePaths
      show.value = true
    },
  })
}
const { startUpload, UPLOAD_STATUS } = useUpload()
async function handleConfirm(event) {
  const { tempFilePath } = event
  userInfo.value.avatar = tempFilePath
  const file: UploadFileItem = {
    url: tempFilePath,
    status: UPLOAD_STATUS.PENDING,
    percent: 0,
    uid: new Date().getTime(),
  }
  try {
    // 开始上传
    await startUpload(file, {
      action: fileUploadNoDomainUrl,
      header: {
        Authorization: `Bearer ${getAccessToken()}`,
      },
      async onSuccess(res) {
        toast.success({
          msg: '上传成功',
        })
        const dataParse = JSON.parse(res.data)
        if (dataParse.code === 0) {
          await updateWorkerAvatar({ avatar: dataParse.data })
        }
      },
      onError() {
        toast.error({
          msg: '上传失败',
        })
      },
      onProgress(res) {
        console.log('上传进度:', res.progress)
      },
    })
  }
  catch (error) {
    console.error('上传失败:', error)
  }
}
function handleCancel(event) {
  // console.log('取消', event)
}
function handleEditInfo() {
  basic_info_form.value.open()
}
function showCertificate(item: QualificationOptionType) {
  certificate_list.value.open(item)
}
function showScorePage() {
  score_list.value.open()
}
function showPasswordSetting() {
  password_setting.value.open()
}
async function _getUserInfo() {
  const res = await getUserInfo()
  Object.assign(userInfo.value, res ?? {})
}
const _getUploadQualificationOptions = async() => {
  const res = await getUploadQualificationOptions()
  qualificationOptions.value = res
}
const handleLogout = () => {
  message
    .confirm({
      msg: '确认登出？',
      title: '提示',
      confirmButtonProps: {
        type: 'error'
      }
    })
    .then(() => {
      LogOutFn()
    })
}
onShow(async () => {
  _getUserInfo()
  _getUploadQualificationOptions()
})
</script>

<template>
  <view class="mePage h-full bg-main">
    <wd-navbar title="个人中心" />
    <view class="me_top_sec bg-primary">
      <wd-img-cropper
        v-model="show"
        :img-src="src"
        @confirm="handleConfirm"
        @cancel="handleCancel"
      />
      <view class="profile_sec">
        <view v-if="!renderInfo.avatar" class="img" @click="upload">
          <wd-icon name="fill-camera" custom-class="img-icon" />
        </view>
        <wd-img
          v-if="renderInfo.avatar"
          round
          width="60px"
          height="60px"
          :src="renderInfo.avatar"
          mode="aspectFit"
          custom-class="profile-img"
          @click="upload"
        />
        <view class="font-bold">
          {{renderInfo.nickname}}
        </view>
        <view class="flex items-center gap-3">
          <wd-rate :model-value="renderInfo.rating" />
          <text>服务评分{{renderInfo.rating}}</text>
        </view>
        <view class="mt-2 w-full flex justify-evenly">
          <view class="flex flex-col items-center">
            <text>{{renderInfo.completeOrderCount}}</text>
            <text class="text-xs">
              完成工单
            </text>
          </view>
          <view class="flex flex-col items-center">
            <text>{{renderInfo.applauseRate_format}}</text>
            <text class="text-xs">
              好评率
            </text>
          </view>
          <view class="flex flex-col items-center">
            <text>{{renderInfo.monthCompleteOrderCount}}</text>
            <text class="text-xs">
              本月工单
            </text>
          </view>
        </view>
      </view>
    </view>
    <view class="shadow-xs m-1 rounded-md p-1">
      <wd-cell-group title="" border>
        <wd-cell title="个人信息" value="修改" is-link @click="handleEditInfo">
          <!-- <template #icon>
            <i class="iconfont icon-personal-info-fill mr-1" />
          </template> -->
        </wd-cell>
        <wd-cell title="设置密码" is-link @click="showPasswordSetting">
          <!-- <template #icon>
            <i class="iconfont icon-personal-info-fill mr-1" />
          </template> -->
        </wd-cell>
        <wd-cell title="客户评价" is-link @click="showScorePage">
          <!-- <template #icon>
            <i class="iconfont icon-score mr-1" />
          </template> -->
        </wd-cell>
      </wd-cell-group>
      <wd-cell-group v-if="qualificationOptions.length" title="技能认证" border custom-class="group">
        <wd-cell v-for="qItem in qualificationOptions" :key="qItem.qualificationType" :title="qItem.qualificationName"
          is-link @click="showCertificate(qItem)">
          <!-- <template #icon>
            <i class="iconfont icon-skill mr-1" />
          </template> -->
          <!-- <view class="custom-text">
            3项证书
          </view> -->
        </wd-cell>
      </wd-cell-group>
    </view>
    <!-- <view class="shadow-xs mx-2 rounded-md bg-white p-1">
      <view class="h-8 text-center leading-8" @click="handleLogout">
        退出登录
      </view>
    </view> -->
    <view class="shadow-xs mx-2 rounded-md">
      <wd-button type="error" block @click="handleLogout">退出登录</wd-button>
    </view>
    <DiaBasicInfoForm ref="basic_info_form" />
    <PopCertificateList ref="certificate_list" />
    <PopScoreList ref="score_list" />
    <PopPasswordSetting ref="password_setting" />
  </view>
</template>

<style lang="scss">
.mePage {
  .group {
    margin-top: 16rpx;
  }
}
.me_top_sec {
  color: #fff;
  .profile_sec {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
    // height: 300px;
    gap: 20rpx;
    padding: 40rpx 0;

    .img {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      // background-color: rgba(0, 0, 0, 0.04);
      position: relative;
      @apply bg-gray-200;
      .img-icon {
        font-size: 30px;
        color: #fff;
        position: absolute;
        left: 50%;
        top: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
      }
    }
  }
}
.wd-img-cropper {
  z-index: 2 !important;
}
</style>
